# Maintainer: umarcor <unai.martinezcorral@ehu.eus>

_realname=nextpnr
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.6
pkgrel=3
pkgdesc="Portable FPGA place and route tool (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64' 'clang32')
url="https://github.com/YosysHQ/nextpnr"
license=('spdx:ISC')
groups=("${MINGW_PACKAGE_PREFIX}-eda")
depends=(
  "${MINGW_PACKAGE_PREFIX}-boost"
  "${MINGW_PACKAGE_PREFIX}-omp"
  "${MINGW_PACKAGE_PREFIX}-python"
  "${MINGW_PACKAGE_PREFIX}-qt5-base"
)
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-cc"
  "${MINGW_PACKAGE_PREFIX}-cmake"
  "${MINGW_PACKAGE_PREFIX}-ninja"
  "${MINGW_PACKAGE_PREFIX}-eigen3"
  "${MINGW_PACKAGE_PREFIX}-icestorm"
  #"${MINGW_PACKAGE_PREFIX}-prjtrellis" Fails to build against v1.4
  "git"
)
source=("${_realname}::git+https://github.com/YosysHQ/${_realname}.git#tag=${_realname}-${pkgver}")
sha256sums=('SKIP')

# pkgver() {
#   cd "${_realname}"
#   git describe --long --tags "${_commit}" | sed 's/nextpnr-//;s/\([^-]*-g\)/r\1/;s/-/./g;s/^v//g'
# }

prepare() {
  cd "${srcdir}/${_realname}"
  git submodule update --init --recursive --depth=1
}

build() {
  mkdir -p "${srcdir}"/build-${MSYSTEM} && cd "${srcdir}"/build-${MSYSTEM}

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  unset _extra-archs
  # if [ "$CARCH" = "x86_64" ]; then
  #   _extra_archs=";ecp5"
  # fi

  _pyver=$(${MINGW_PREFIX}/bin/python -c "import sys;sys.stdout.write('.'.join(map(str, sys.version_info[:2])))")

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -G "Ninja" \
    -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
    "${_extra_config[@]}" \
    -DICESTORM_INSTALL_PREFIX="${MINGW_PREFIX}" \
    -DTRELLIS_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_PREFIX_PATH=${MINGW_PREFIX} \
    -DARCH="generic;ice40${_extra_archs}" \
    -DBUILD_HEAP=ON \
    -DUSE_OPENMP=ON \
    -DUSE_IPO=OFF \
    -DBUILD_PYTHON=ON \
    -DBUILD_GUI=ON \
    -DBUILD_TESTS=OFF \
    -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python \
    -DPython3_LIBRARY=${MINGW_PREFIX}/lib/libpython${_pyver}.dll.a \
    ../${_realname}

  ${MINGW_PREFIX}/bin/cmake --build .
}

check() {
  cd "${srcdir}"/build-${MSYSTEM}
  ${MINGW_PREFIX}/bin/cmake -DBUILD_TESTS=ON ../${_realname}
  ${MINGW_PREFIX}/bin/cmake --build .
  ${MINGW_PREFIX}/bin/ctest
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .

  _licenses="${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}"
  mkdir -p "${_licenses}"
  install -m 644 "${srcdir}/${_realname}"/COPYING "${_licenses}"
}
